﻿using zijian666.Converts.Abstractions;
using zijian666.Converts.Core;

namespace zijian666.Converts.Convertor.Base;

/// <summary>
/// 代理转换器
/// </summary>
/// <remarks>
/// 转换器输出类型可兼容, 但不能直接协变时, 可使用代理方式执行
/// </remarks>
public class ProxyConvertor<TProxy, TOutput> : IProxyConvertor<TProxy>, IConvertor<TOutput>
    where TProxy : TOutput
{
    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="convertor"></param>
    public ProxyConvertor(IConvertor<TProxy> convertor) =>
        InnerConvertor = (convertor as IProxyConvertor<TProxy>)?.InnerConvertor ?? convertor;

    /// <inheritdoc/>
    public uint Priority => InnerConvertor.Priority;

    /// <summary>
    /// 被代理的转换器
    /// </summary>
    public IConvertor<TProxy> InnerConvertor { get; }

    /// <inheritdoc />
    public ConvertResult<TOutput> Convert(IConvertContext context!!, object? input)
    {
        var result = InnerConvertor.Convert(context, input);
        if (result.Success)
        {
            return new ConvertResult<TOutput>(result.Value);
        }
        return result.Exception!;
    }
}
